<template>
  <view class="pay-list">
    <uni-list>
      <uni-list-item
        thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
        thumb-size="min"
        title="楼栋"
        @click="buildingClick"
        link
        :rightText="building"
      />
      <uni-list-item
        thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
        thumb-size="min"
        title="楼层"
        @click="floorClick"
        link
        :rightText="floor"
      />
      <uni-list-item
        thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
        thumb-size="min"
        title="户号"
        @click="accountClick"
        link
        :rightText="account"
      />
<!--      <uni-list-item
        thumb="https://minio.gzryzl.com/huatai/2024-08-26/1724677657062必填.png"
        thumb-size="min"
        title="付款周期"
        @click="payCycleClick"
        link
        :rightText="payCycle"
      />
      <uni-list-item
        title="所缴月份"
        @click="payDateClick"
        :rightText="payDate"
      />
      <uni-list-item
        title="物业费"
        :rightText="propertyFee"
      />
      <uni-list-item
        title="应付金额"
        :rightText="payAccount"
      />
      <uni-list-item
		v-if="nextPayTime"
        title="下次缴费时间"
        :rightText="nextPayTime"
      />-->
    </uni-list>
    <!-- <view class="card_box">
      <historicalArrears
        v-for="item in infoData"
        :key="item.id"
        :infoData="item"
        :activeId="order"
        @on-change="headelChange"
      >
      </historicalArrears>
      <view class="expiration_box" v-if="expiration !== ''">
        <view class="expiration_text" v-if="!isNotADate(expiration)">
          还未到最新缴费时间，下次缴费时间为{{
            expiration
          }}，请于缴费时间再来缴费</view
        >
        <view class="expiration_text" v-else> {{ expiration }}</view>
      </view>
    </view> -->
  <!--  <none-data
      v-if="
        infoData.length === 0 && expiration == '' && account !== '请选择户号'
      "
    /> -->
	<view class="record-box">
		<view
		  v-for="(item, index) in recordList"
		  class="historical-arrears"
		  @click="fatherChange(item, index)"
		  :class="fatherChangeItem.id === item.id ? 'select' : ''"
		>
		  <view class="title">物业缴费</view>
		  <view class="information">
		    <view class="information_box">
		      <view class="information_item">缴费月份：{{ item?.arrearsMonth }}</view>
		      <view class="information_item"
		        >物业费：{{monthly}} 元 / ㎡</view
		      >
		      <view class="information_item"
		        >房间面积：{{item?.area}} ㎡</view
		      >
		      <view class="information_item"
		        >应缴金额：{{ item?.meetMoney }} 元</view
		      >
<!--		      <view class="information_item"
		        >缴费时间：{{
		          item?.payTime
		        }}</view
		      >-->

          <view class="information_item"
          >备注：{{ item?.notes }}</view
          >
          <view class="information_item"
          >支付状态：{{ item?.userPayStatus == '0' ? '未支付': '已支付' }}</view
          >

          <view class="information_item">
            <view class="room">
              <p>注：</p>
              您正在对房间{{ item?.accountNumber }}进行缴费，请确认金额和房号，如缴错费用，系统不支持退费，请线下联系客服办理退费手续。
            </view>
          </view>
        </view>

        <view class="ch" v-if="item.userPayStatus === '0'">
          <up-checkbox
              size="28rpx"
              name="agree"
              :usedAlone="true"
              :checked="aloneCheckedIndex === index"
          >
          </up-checkbox>
        </view>
		  </view>
		</view>
	</view>

    <view class="outstanding-charges" v-if="propertyOrderCount === 0 && account != '请选择户号'">未欠费</view>
	
    <up-picker
      :show="buildingShow"
      @confirm="headelBuildingSaveClick"
      @cancel="buildingShow = false"
      :columns="buildingList"
      keyName="name"
    ></up-picker>
    <up-picker
      :show="floorShow"
      @confirm="headelFloorSaveClick"
      @cancel="floorShow = false"
      :columns="floorList"
      keyName="name"
    ></up-picker>
    <up-picker
      :show="accountShow"
      @confirm="headelAccountSaveClick"
      @cancel="accountShow = false"
      :columns="accountList"
      keyName="name"
    ></up-picker>
    <up-picker
      :show="payCycleShow"
      @confirm="headelPayCycleSaveClick"
      @cancel="payCycleShow = false"
      :columns="payCycleList"
      keyName="name"
    ></up-picker>
<!--    <up-picker
      :show="payDateShow"
      @confirm="headelPayDateSaveClick"
      @cancel="payDateShow = false"
      :columns="payDateList"
      keyName="name"
    ></up-picker> -->
    <up-modal
      :show="pattern"
      @confirm="payBroadbandOrder"
      @cancel="pattern = false"
      ref="uModal"
      :showCancelButton="true"
      :asyncClose="true"
    >
<!--      <view class="box">
        <view class="title"> 缴费确认 </view>
        <view class="content_box">
          您正在对房间
          <text class="room">
            {{ account }}</text>进行缴费，请确认金额和房号，如缴错费用，概不退款，请认真检查
        </view>
      </view>-->
      <view class="box">
        <view class="title"> 缴费确认 </view>
        <view class="content_box">
          <view class="i">户号：{{parseInt(building)}}-{{account}}</view>
          <view class="i">缴费类别：物业缴费</view>
          <view class="i">缴费金额：{{ fatherChangeItem.meetMoney }}</view>
        </view>
      </view>
    </up-modal>
    <view class="room-btn broadband">
      <button
        class="btn lose"
        v-if="propertyOrderCount === 0 || (account == '请选择户号')" @click="onSubmit">
        确认缴费
      </button>
      <button class="btn" v-else @click="onSubmit">确认缴费</button>
      <!-- <button class="btn" v-if="indicate" @click="jump">确认缴费</button> -->
    </view>
  </view>
</template>

<script setup>
import {
  getPropertyFeeBroadbandCorporateListApi,
  getBroadbandCorporateOrderApi,
  getPropertyFeeFloorListApi,
  getBroadbandOnLineApi,
  getRoomPropertyFeeApi,
  payHousePropertyFeeOrderApi,
  getHousePropertyFeeOrderRecordListApi,
  getPropertyOrderPageApi, payPropertyOrderApi
} from "@/package_property/pages/api/broadband.js";
import { getDictConfigListByType } from "@/package_property/pages/api/home.js";
import { payBroadbandOrderApi } from "@/package_property/pages/api/my.js";
import UniListItem from "@/uni_modules/uni-list/components/uni-list-item/uni-list-item.vue";
import UniList from "@/uni_modules/uni-list/components/uni-list/uni-list.vue";
import historicalArrears from "@/package_property/pages/components/historical-arrears/index.vue";
import {defineEmits, defineProps, ref} from "vue";
import { customNav } from "../../../utils/customNav";
import { useNewFormatDate } from "../../../utils/formatHooks";
import { accMul } from "../../../utils/mathFixed";
import { onLoad, onShow } from "@dcloudio/uni-app";
const order = ref("");
const orderData = ref({});
const building = ref("请选择楼栋");
const buildingId = ref("");
const floor = ref("请选择楼层");
const account = ref("请选择户号");
const payCycle = ref("请选择付款周期");
const payDate = ref("-");
const propertyFee = ref("0.00元/月");
const payAccount = ref("0.00元");
const payNextDate = ref("");
const monthly = ref("");
const expiration = ref("");
const nextPayTime = ref("");
const indicate = ref(false);
const buildingShow = ref(false);
const floorShow = ref(false);
const accountShow = ref(false);
const payCycleShow = ref(false);
const payDateShow = ref(false);
const pattern = ref(false);
const isLockedPayCycle = ref(false);
const payStatus = ref(1);
const pageData = ref({
  page: 1,
  size: 10,
});
const buildingList = ref([
  [
    {
      name: "1单元",
      id: "1",
    },
    {
      name: "2单元",
      id: "2",
    },
  ],
]);
const floorList = ref([[]]);
const accountList = ref([[]]);
const infoData = ref([]);
const recordList = ref([]);
const payCycleList = ref([
  [
    {
      name: "月付",
      id: "1",
    },
    {
      name: "季付",
      id: "2",
    },
    {
      name: "年付",
      id: "3",
    },
  ],
]);
const payDateList = ref([]);
function buildingClick() {
  buildingShow.value = true;
}
function floorClick() {
  if (floorList.value[0].length !== 0) {
    floorShow.value = true;
  } else {
    uni.showToast({ title: "请选择楼栋", duration: 2000, icon: "none" });
  }
}
function accountClick() {
  if (accountList.value[0].length !== 0) {
    accountShow.value = true;
  } else {
    uni.showToast({ title: "请选择楼层", duration: 2000, icon: "none" });
  }
  fatherChangeItem.value = {}
  aloneCheckedIndex.value = -1
}

function payCycleClick() {
  if(isLockedPayCycle.value){
	  uni.showToast({ title: "该户号已选定付款周期，无法更改哦", duration: 2000, icon: "none" });
	  getRoomPropertyFee()
	  return
  }
  if (accountList.value[0].length !== 0 && (account && account.value != '请选择户号')) {
    payCycleShow.value = true;
  } else {
    uni.showToast({ title: "请选择户号", duration: 2000, icon: "none" });
  }
}

function payDateClick() {
  if (payCycle.value && payCycle.value != '请选择付款周期') {
    payDateShow.value = true;
  } else {
    uni.showToast({ title: "请选择付款周期", duration: 2000, icon: "none" });
  }
}

function headelBuildingSaveClick(n) {
  building.value = n.value[0].name;
  buildingId.value = n.value[0].id;
  buildingShow.value = false;
  floor.value = "请选择楼层"
  account.value = "请选择户号"
  propertyFee.value = "0.00元/月"
  payAccount.value = "0.00元"
  nextPayTime.value = ''
  payDate.value = '-'
  payCycle.value = '请选择付款周期'
  isLockedPayCycle.value = false
  recordList.value = []
  floorList.value = [[]]
  accountList.value = [[]]
  payStatus.value = 1
  getFloorListData();
}
function headelFloorSaveClick(n) {
  floor.value = n.value[0].name;
  floorShow.value = false;
  account.value = "请选择户号"
  propertyFee.value = "0.00元/月"
  payAccount.value = "0.00元"
  nextPayTime.value = ''
  payDate.value = '-'
  payCycle.value = '请选择付款周期'
  isLockedPayCycle.value = false
  recordList.value = []
  accountList.value = [[]]
  payStatus.value = 1
  getBroadbandCorporateList();
}
function headelAccountSaveClick(n) {
  console.log("change", n);
  account.value = n.value[0].name;
  accountShow.value = false;
  propertyFee.value = "0.00元/月"
  payAccount.value = "0.00元"
  nextPayTime.value = ''
  payDate.value = '-'
  payCycle.value = '请选择付款周期'
  recordList.value = []
  isLockedPayCycle.value = false
  payStatus.value = 1
  getBroadbandOnLine();
}
function headelPayCycleSaveClick(n) {
  payCycle.value = n.value[0].name;
  payCycleShow.value = false;
  isLockedPayCycle.value = false
  getRoomPropertyFee()
  // getPayDate()
}

function headelChange(data) {
  console.log("组件参数", data);
  order.value = data?.id;
  orderData.value = data;
}

async function getFloorListData() {
  let res = await getPropertyFeeFloorListApi(buildingId.value);
  const { code, data } = res || {};
  if (code == 200) {
    console.log("getFloorListApi", data);
    floorList.value[0] = data.map((o) => {
      return {
        name: o,
      };
    });
  }
}
async function getBroadbandCorporateList() {
  let res = await getPropertyFeeBroadbandCorporateListApi({
    unit: buildingId.value,
    floor: floor.value,
  });
  const { code, data } = res || {};
  if (code == 200) {
    console.log("getBroadbandCorporateListApi", data);
    accountList.value[0] = data.map((o) => {
      return {
        name: o,
      };
    });
  }
}
async function getBroadbandCorporateOrder() {
  let res = await getBroadbandCorporateOrderApi({
    page: pageData.value.page,
    size: pageData.value.size,
    accountNumber: account.value,
  });
  const { code, data } = res || {};
  if (code == 200) {
    console.log("getBroadbandCorporateOrderApi", data);
    let info = data.records.map((o) => {
      return {
        id: o.id,
        cycle: o.arrearsMonth,
        monthly: monthly.value,
        payable: o.meetMoney,
        followUp: o.updateTime,
        notes: o.notes,
        payWay: o.payWay,
        userPayStatus: o.userPayStatus,
      };
    });
    if (pageData.value.page !== 1) {
      infoData.value = infoData.value.concat(info);
    } else {
      infoData.value = info;
    }
  }
}

let orderIdHide = ref('')
async function payBroadbandOrder() {
  let type = {
    orderId: order.value,
    // #ifdef MP-WEIXIN
    payType: "0",
    // #endif
    // #ifndef MP-WEIXIN
    payType: "1",
    // #endif
  };
  console.log(type);
  if (account.value == "请选择户号") {
	uni.showToast({ title: "请选择户号", duration: 2000, icon: "none" });
	return
  }
  console.log('1111111111111111')
  pattern.value = true;
  const res = await payPropertyOrderApi({
    orderId: fatherChangeItem.value.id,
    payType: type.payType,
    meetMoney: fatherChangeItem.value.meetMoney + ''
  });
  console.log('ss---------------', res)
  const { code, data } = res || {};
  if (code == 200) {
    orderIdHide.value = fatherChangeItem.value.id
    // console.log("data",data);
    // #ifdef MP-WEIXIN
    weixinClick(data);
    // #endif
    // #ifndef MP-WEIXIN
    weChatAppPay(data);
    // #endif
  }
}
/**
 * 唤起支付
 * @param payData
 */
const weixinClick = (payData) => {
  uni.requestPayment({
    provider: "wxpay",
    timeStamp: payData.timeStamp,
    nonceStr: payData.nonceStr,
    package: payData.prepayId,
    signType: payData.signType,
    paySign: payData.paySign,
    success: function (res) {
      console.log("success:" + JSON.stringify(res));
      uni.showToast({
        title: "支付成功",
        duration: 2000,
        success: () => {
          pattern.value = false;
          pageData.value.page = 1;
          getBroadbandOnLine();
        },
      });
    },
    fail: function (err) {
      orderIdHide.value = ''
      pattern.value = false;
      if (err.errMsg == "requestPayment:fail cancel")
        return uni.showToast({
          title: "您已取消支付",
          duration: 2000,
          icon: "none",
        });
      uni.showToast({ title: "支付失败", duration: 2000, icon: "none" });
      console.log("fail:" + JSON.stringify(err));
    },
  });
};

// 微信APP支付
const weChatAppPay = (payData) => {
  let params = {
    partnerId: payData.partnerId, //商户号
    prepayId: payData.prepayId, //预支付交易会话ID
    nonceStr: payData.nonceStr, //随机字符串
    timeStamp: payData.timeStamp, //时间戳
    sign: payData.paySign, //签名
  };
  window.mobile.jsCallPayWx(JSON.stringify(params));
};
// async function getBroadbandOnLine() {
//   expiration.value = "";
//   infoData.value = [];
//   const res = await getHousePropertyFeeOrderRecordListApi({
//     unit: buildingId.value,
//     floor: floor.value,
//     roomNumber: account.value,
// 	page: 1,
// 	size: 9999,
//   });
//   const { code, data } = res || {};
//   if (code == 200) {
//     console.log("getHousePropertyFeeOrderRecordListApi", data);
// 	recordList.value = data.page.records
// 	isLockedPayCycle.value = data.payPeriodStatus != 0
// 	payCycle.value = data.payPeriodStatus == 1 ?  '月付' : data.payPeriodStatus == 2 ? '季付' : data.payPeriodStatus == 4? '年付' : '请选择付款周期'
// 	if(isLockedPayCycle.value)  getRoomPropertyFee()
//   }
// }

async function getRoomPropertyFee() {
  expiration.value = "";
  infoData.value = [];
  const res = await getRoomPropertyFeeApi({
    unit: buildingId.value,
    floor: floor.value,
    roomNumber: account.value,
	payPeriodStatus: payCycle.value == '月付' ?  1 : payCycle.value == '季付' ? 2 : payCycle.value == '年付'? 4 : '' 
  });
  const { code, data } = res || {};
  if (code == 200) {
    console.log("getRoomPropertyFeeApi", data);
	propertyFee.value = data.propertyFee + '元/月';
	nextPayTime.value = data.nextPayTime 
	payDate.value = data.needPayMonth
	payStatus.value = data.payStatus
	let mul = 0
	if(data.payPeriodStatus == 0) {
		mul = payCycle.value == '月付' ?  1 : payCycle.value == '季付' ? 3 : payCycle.value == '年付'? 12 : ''
	} else {
		mul = data.payPeriodStatus == 1 ?  1 : data.payPeriodStatus == 2 ? 3 : data.payPeriodStatus == 4? 12 : ''
	}
	payAccount.value = accMul(mul, data.propertyFee)
  }
}

function getPayDate() {
	// switch (payCycle.value) {
	//     case "月付":
	// 		payDateList.value[0]= [1,2,3,4,5,6,7,8,9,10,11,12]
	//         break;
	//     case "季付":
	// 		payDateList.value[0] = [1,2,3,4,5,6,7,8,9,10,11,12]
	//         break;
	//     case "年付":
	// 		const tempDate = new Date();
	// 		const nextTempData = new Date(tempDate.getTime() + 31536000000);
	// 		const tempDateStr = useNewFormatDate(tempDate)
	// 		// tempDate.getFullYear()
	// 		console.log('nextTempData======', nextTempData.getDate())
	// 		payDateList.value[0] = ['全年']
	//         break;
	//     default:
	// 		payDateList = []
	//         break;
	// }
	
}


function jump() {
  customNav(`pay-details?room=${account.value}&down=${indicate.value}`);
}
function loseClick() {
  if (account.value == "请选择户号") {
    uni.showToast({ title: "请选择户号", duration: 2000, icon: "none" });
  } else if (!isNotADate(expiration.value)) {
    uni.showToast({
      title: "请等到下次缴费日期时，再来进行缴费",
      duration: 2000,
      icon: "none",
    });
  } else {
    uni.showToast({ title: expiration.value, duration: 2000, icon: "none" });
  }
}
function isNotADate(value) {
  const date = new Date(value);
  return isNaN(date.getTime());
}
async function onSubmit(value) {
  if (account.value == "请选择户号") {
	uni.showToast({ title: "请选择户号", duration: 2000, icon: "none" });
	return
  }

  if (Object.keys(fatherChangeItem.value).length === 0) {
    uni.showToast({ title: "未选择缴费账单", duration: 2000, icon: "none" });
    return
  }
  pattern.value = true;
}

onLoad(() => {
  getBroadbandMonthlyRent()
});
onShow(() => {
  if (account.value !== "请选择户号") {
    getBroadbandOnLine();
  }
});

let propertyOrderCount = ref(0)
// getBroadbandOnLine >> getPropertyOrderPage
// 上面都是这样写的...
async function getBroadbandOnLine() {
  expiration.value = "";
  infoData.value = [];
  const res = await getPropertyOrderPageApi({
    userPayStatus: '0',
    accountNumber: account.value,
    page: 1,
    size: 9999,
  })
  const { code, data } = res || {};
  if (code == 200) {
    console.log("getPropertyOrderPageApi123", data);

    propertyOrderCount.value = data.total
    recordList.value = data.records.filter(item => item.id !== orderIdHide.value)
    console.log("getPropertyOrderPageApi321", orderIdHide.value);
    console.log("getPropertyOrderPageApi444", recordList.value);

    /*isLockedPayCycle.value = data.payPeriodStatus != 0
    payCycle.value = data.payPeriodStatus == 1 ?  '月付' : data.payPeriodStatus == 2 ? '季付' : data.payPeriodStatus == 4? '年付' : '请选择付款周期'
    if(isLockedPayCycle.value)  getRoomPropertyFee()*/
  }
}

// 物业月租
async function getBroadbandMonthlyRent() {
  const res = await getDictConfigListByType("1831580314393654364");
  const { code, data } = res || {};
  if (code == 200) {
    monthly.value = Number(data[0].children[0].filedName);
  }
}

let aloneCheckedIndex = ref(-1)
let fatherChangeItem = ref({})
function fatherChange(e, i) {
  if(aloneCheckedIndex.value === i) {
    fatherChangeItem.value = {}
    aloneCheckedIndex.value = -1
  } else {
    fatherChangeItem.value = e
    aloneCheckedIndex.value = i
  }
  console.log(e)
}
</script>

<style lang="less">
.record-box{
  padding-top: 20rpx;
  padding-bottom: 200rpx;
  display: flex;
  flex-direction: column;
  align-items: center;
}
.historical-arrears {
  width: 80vw;
  border: 1rpx solid #d7d7d7;
  background: #ffffff;
  border-radius: 10rpx;
  padding: 30rpx;
  margin-top: 20rpx;
  .title {
    color: #333333;
    text-align: center;
    margin-bottom: 30rpx;
    font-size: @font-size-36;
  }
  .information {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    align-items: center;
    .information_box {
      padding-inline-start: 0;
      .information_item {
        list-style-type: none;
        margin: 15rpx 0;
        font-weight: 400;
        color: #333333;
      }
    }
  }
  &.select {
    background-color: #3ec2ff;
    .title {
      color: @color-font;
    }
    .information {
      .information_box {
        .information_item {
          color: @color-font;
        }
      }
    }
  }
}
.card_box {
  width: 100vw;
  display: flex;
  flex-flow: column nowrap;
  align-items: center;
  padding: 20rpx 0;
  max-height: 73vh;
  overflow-y: scroll;
  .expiration_box {
    width: 100%;
    height: 200rpx;
    display: flex;
    flex-flow: row nowrap;
    justify-content: center;
    margin-top: 30rpx;
    .expiration_text {
      width: 70%;
      text-align: center;
    }
  }
}
.box {
  display: flex;
  flex-flow: row wrap;
  justify-content: center;
  .title {
    width: 100%;
    font-size: @font-size-39;
    text-align: center;
    font-weight: bold;
    margin-bottom: 20rpx;
  }
  .room {
    font-size: @font-size-39;
    font-weight: bold;
    color: @color-red;
  }
}

.outstanding-charges {
  text-align: center;
  margin-top: 40rpx;
  color: #3b4144;
  font-size: 30rpx;
  font-family: "ali";
}
.room{
  font-size: @font-size-39;
  color: @color-red;
}
</style>